package org.yang.loginunion.core.email;

import org.apache.commons.lang3.StringUtils;
import org.yang.loginunion.core.LoginClient;
import org.yang.loginunion.core.constants.IdentityType;
import org.yang.loginunion.core.exception.LoginException;
import org.yang.loginunion.core.repository.OauthRepository;
import org.yang.loginunion.core.repository.OauthTempRepository;
import org.yang.loginunion.core.repository.VerifycodeRepository;

/**
 * Description: 邮箱+验证码登录
 *
 * @author Billyang
 * @date 2024/8/3 16:03
 */
public class EmailCodeClient implements LoginClient {

    private OauthRepository oauthRepository;

    private VerifycodeRepository verifycodeRepository;

    public EmailCodeClient(OauthRepository oauthRepository, VerifycodeRepository verifycodeRepository) {
        this.oauthRepository = oauthRepository;
        this.verifycodeRepository = verifycodeRepository;
    }

    @Override
    public String login(String email, String code, String ignore3) {
        if (StringUtils.isAnyBlank(email, code)) {
            throw new LoginException("缺失参数");
        }
        //核对验证码
        boolean checkVerifycode = verifycodeRepository.checkVerifycode(email, code);
        if (!checkVerifycode) {
            throw new LoginException("验证码错误");
        }
        //获取用户
        String userId = oauthRepository.getUserId(IdentityType.EMAIL, email);
        if (userId == null) {
            userId = oauthRepository.registerUser(IdentityType.EMAIL, email);
        }
        return userId;
    }
}
